package com.lw;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

	@GetMapping("/api/protected")
	public @ResponseBody Object hellWorld() {
		return "Hello World! This is a protected api";
	}

	@PostMapping("/login")
	public void login(HttpServletResponse response, @RequestBody final AccountCredentials credentials)
			throws IOException {
		// here we just have one hardcoded username=admin and password=admin
		// TODO add your own user validation code here
		if (validCredentials(credentials)) {
			String jwt = JwtUtil.generateToken(credentials.username);
			response.addHeader(JwtUtil.HEADER_STRING, JwtUtil.TOKEN_PREFIX + " " + jwt);
		} else
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong credentials");
	}

	private boolean validCredentials(AccountCredentials credentials) {
		return "admin".equals(credentials.username) && "admin".equals(credentials.password);
	}
}
